import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Search from '@/views/search'
import SearchList from '@/views/search/list.vue'
import Prodetail from '@/views/prodetail'
import Pay from '@/views/pay'
import MyOrder from '@/views/myorder'
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/prodetail/:id', component: Prodetail },
    {
      path: '/pay',
      component: Pay,
      meta: { requiresAuth: true }
    // 需要权限
    },
    {
      path: '/myorder',
      component: MyOrder,
      meta: { requiresAuth: true }
    }
  ]
})

// 全局前置导航守卫
// to：到哪去，完整路由信息对象（路径，参数）
// from：从哪里来 完整路由信息对象（路径，参数）
// next 是否放行
// 1.next() 直接放行 ，放行到to
// 2.next(路径) 进行拦截 拦截到next

// 定义一个数组,储存用户需要权限的地址
// 注册全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查目标路由是否需要权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 这里可以根据你的需求进行权限验证，例如检查用户是否已登录
    const isAuthenticated = store.state.isAuthenticated// 假设你在 Vuex 中有一个 `isAuthenticated` 状态

    if (!isAuthenticated) {
      // 如果用户未登录，显示提示信息
      Notification.warning({
        title: '未登录',
        message: '请先登录后再访问该页面。',
        duration: 3000 // 提示持续时间
      })
      // 如果用户未登录，重定向到登录页面
      next({ path: '/login' })
    } else {
      // 用户已登录，放行
      next()
    }
  } else {
    // 不需要权限，直接放行
    next()
  }
})

export default router
